package com.aaa.service.impl;

import com.aaa.dao.RoleDao;
import com.aaa.dao.impl.RoleDaoImpl;
import com.aaa.entity.Role;
import com.aaa.service.RoleService;
import com.aaa.util.DefaultMsg;
import com.aaa.util.TableData;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class RoleServiceImpl implements RoleService {
    @Autowired
    private RoleDao roleDao;
    public TableData<Role> listAll(String keyword) {
        TableData<Role> tableData = new TableData<Role>();
        List<Role> roles = roleDao.listAll(keyword);
        tableData.setData(roles);
        return tableData;
    }

    public Role findById(Long id) {
        return null;
    }

    public DefaultMsg saveOrUpdate(Role role,String rids) {
        DefaultMsg defaultMsg = new DefaultMsg();
        Integer count;
        Integer rid =role.getId();
        if(rid==null){
            //保存角色
            rid=roleDao.save(role);
        }else {
            count=roleDao.update(role);
            if(count==0){
                throw  new RuntimeException("保存用户角色失败");
            }
            //删除角色原先能操作的模块
            count = roleDao.deleteRoleMenu(rid);
        }
        //保存角色能操作的菜单
        for(String ridStr : rids.split(",")){
            count = roleDao.saveRoleMenu(rid,Integer.valueOf(ridStr));
            if(count==0){
                throw  new RuntimeException("保存用户角色失败");
            }
        }
        return defaultMsg;
    }

    public DefaultMsg delete(Long id) {
        return null;
    }


    public DefaultMsg delete(Integer id) {
        DefaultMsg defaultMsg = new DefaultMsg();
        Integer delete = roleDao.delete(id);
         roleDao.deleteRoleMenu(id);
        if (delete==0){
            defaultMsg.setError("操作失败");
        }
        return defaultMsg;
    }

    public List<Integer> checkIdRole(Integer id) {
        return roleDao.checkIdRole(id);
    }
}
